package com.lzy.sms.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.lzy.properties.AliyunSmsProperties;
import com.lzy.sms.SmsService;
import com.lzy.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 短信发送服务
 *
 * @author lzy by 2019/9/10 11:40
 */
@Slf4j
public class AliyunSmsServiceImpl implements SmsService {

    private AliyunSmsProperties properties;
    /**
     * 发送成功返回标识
     */
    private static final String SEND_MSM_SUCCESS_KEY = "OK";

    /**
     * 发送短信验证码
     *
     * @param phoneNum     手机号
     * @param validCode    验证码
     * @param templateCode 短信模板
     * @return
     */
    @Override
    public boolean sendValidCode(String phoneNum, String validCode, String templateCode) {
        return sendValidCode(phoneNum, validCode, templateCode, new HashMap<>());
    }

    /**
     * 发送短信验证码
     *
     * @param phoneNum     手机号
     * @param validCode    验证码
     * @param templateCode 短信模板
     * @param paramMap     参数
     * @return
     */
    @Override
    public boolean sendValidCode(String phoneNum, String validCode, String templateCode, Map<String, String> paramMap) {
        DefaultProfile profile = DefaultProfile.getProfile("default", properties.getAccessKeyId(), properties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "default");
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", properties.getSignName());
        request.putQueryParameter("TemplateCode", templateCode);
        paramMap.put("code", validCode);
        request.putQueryParameter("TemplateParam", new Gson().toJson(paramMap));
        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
        String data = response.getData();
        log.info("手机号码[" + phoneNum + "],发送短信回调:{}", data);
        try {
            Map<String, Object> map = JsonUtils.jsonToMap(data);
            if (map == null) {
                return Boolean.FALSE;
            }
            String code = Optional.ofNullable(map.get("Code")).map(Object::toString).orElse("");
            return SEND_MSM_SUCCESS_KEY.equals(code);
        } catch (Exception e) {
            log.error("短信发送失败['phoneNum':" + phoneNum + ",'templateCode':" + templateCode + "]", e);
            return Boolean.FALSE;
        }
    }




    public AliyunSmsServiceImpl(AliyunSmsProperties aliyunSmsProperties) {
        properties = aliyunSmsProperties;
    }

    public AliyunSmsServiceImpl() {
    }

    public void setAliyunSmsProperties(AliyunSmsProperties aliyunSmsProperties) {
        properties = aliyunSmsProperties;
    }
}
